package mongodb

import (
	"context"
	"fmt"
	"github.com/xinliangnote/go-gin-api/configs"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type dbRepo struct {
	DbClient *mongo.Client
}

type Repo interface {
	i()
	GetDb() *mongo.Client
	DbClose() error
}

func (d *dbRepo) i() {}

func (d *dbRepo) GetDb() *mongo.Client {
	return d.DbClient
}

func (d *dbRepo) DbClose() error {
	return d.DbClient.Disconnect(context.Background())
}

func New() (Repo, error) {
	cfg := configs.Get().Mongodb
	dbr, err := dbConnect(cfg.Config.User, cfg.Config.Pass, cfg.Config.Addr, cfg.Config.Name)
	if err != nil {
		return nil, err
	}

	return &dbRepo{
		DbClient: dbr,
	}, nil
}

func dbConnect(user, pass, addr, dbName string) (*mongo.Client, error) {
	clientOptions := options.Client().ApplyURI("mongodb://" + user + ":" + pass + "@" + addr + "/?authSource=" + dbName)
	// 连接到MongoDB
	client, err := mongo.Connect(context.Background(), clientOptions)
	if err != nil {
		return nil, err
	}
	// 检查连接
	err = client.Ping(context.Background(), nil)
	if err != nil {
		return nil, err
	}
	fmt.Println("成功连接到MongoDB")
	return client, nil
}
